<template>
	<view>
		<view v-if="loading">
			<view class="main-container">
				<view class="title">打卡报到</view>
				<view style="text-align: center; margin-top: 20px;">{{ currTime }}</view>
				<view class="card-container">
					<view v-if="registerInfoVo.sureStatus == 1" class="card" @click="submitForm">立即报到</view>
					<view v-if="registerInfoVo.sureStatus == 2" class="card no-active">已报到</view>
					<view v-if="registerInfoVo.sureStatus == 3" class="card no-active">已过期</view>
				</view>
				<view v-if="registerInfoVo.sureStatus == 1">
					<view class="line">报到位置：{{ registerInfoVo.registerNoticeVo.registerAddress }}</view>
					<view class="line">当前位置：{{ locationInfo.address }}</view>
					<view class="line" v-if="false">当前经纬度：{{ locationInfo.latitude }} {{ locationInfo.longitude }}
					</view>
					<view class="line">报到距离：<span v-if="locationInfo.distance">{{ locationInfo.distance }}米</span>
					</view>
				</view>
			</view>
			<view class="main-container">
				<view class="title">报名信息</view>
				<view class="line">进修科室：{{ registerInfoVo.registerDeptName }}</view>
				<view class="line">进修姓名：{{ registerInfoVo.userName }}</view>
				<view class="line">进修工号：{{ registerInfoVo.registerNoticeVo.jobNumber }}</view>
				<view class="line">进修时长：{{ registerInfoVo.registerNoticeVo.startDate }} ~
					{{ registerInfoVo.registerNoticeVo.endDate }}（{{ registerInfoVo.durationName }}）
				</view>
				<view class="line">申请单位：{{ registerInfoVo.unitHospitalName }}</view>
				<view class="line">申请时间：{{ formatDate(registerInfoVo.applyTime) }}</view>
			</view>
			
			<u-gap height="1" bgColor="#F2F3F5"></u-gap>

			<view class="container-null">
				<u-button type="primary" @click="logout">退出登录</u-button>
			</view>
		</view>
		<u-modal :show="errShow" title="系统提示" :content="errMsg" :showConfirmButton="true" confirmText="退出登录" @confirm="errShow= false;loginOut()"></u-modal>
	</view>
</template>

<script>
	let that;
	export default {
		data() {
			return {
				loading: false,
				currTime: null,
				currTab: 1,
				
				registerInfoVo: {
					registerNoticeVo: {},
				},
				sureInfo: {
					longitude: null,
					latitude: null,
				},
				locationInfo: {
					longitude: null,
					latitude: null,
					address: null,
					distance: null,
				},
				errShow: false,
				errMsg: '',
			}
		},
		onShow() {
			that = this;
			uni.$u.http.get('/au/defaultLogin/beforeLogin').then(res => {
				if (res.code == 200) {
					that.initData();
					that.getLocation()
				} else {
					uni.$u.route('/pages/login/login');
				}
			});
		},
		methods: {
			initData() {
				that.getCurrTime();
				that.getCurrTimeInterval();
				that.getRegisterInfo();
			},
			// 立即报到
			submitForm() {
				if (that.locationInfo.distance <= 200) {
					let registerNoticeVo = Object.assign(that.registerInfoVo.registerNoticeVo);
					registerNoticeVo.sureAddress = that.locationInfo.address
					uni.$u.http.post('/au/registerBase/saveSure', registerNoticeVo).then(res => {
						that.$msg('报到成功');
						that.registerInfoVo.sureStatus = 2;
						// that.getRegisterInfo();
					});
				} else {
					that.$msg('距离太远，无法打卡！');
				}

			},
			tabChange(e) {
				that.currTab = e.id
			},
			getRegisterInfo() {
				uni.$u.http.get('/au/sureInfo/getInfo/1').then(res => {
					that.sureInfo = res.data;
					uni.$u.http.get('/au/registerBase/getLast').then(res2 => {
						if (res2.data) {
							that.loading = true
							that.registerInfoVo = res2.data;
							if (!res2.data.registerNoticeVo) {
								that.registerInfoVo.registerNoticeVo = {};
							}
							if (that.registerInfoVo.sureStatus == 1) {
								// that.getLocation();
							}
						} else {
							that.errMsg = '您还没有报名信息，可以前往PC端进行报名'
							that.errShow = true
						}
					});
				});
			},
			getLocation() {
				uni.showLoading({
					title: '定位中...'
				});
				try {
					uni.getLocation({
						// type: 'gcj02',
						isHighAccuracy: true,
						success(res) {
							console.log('成功', res)
							if (res.errMsg == 'getLocation:ok') {
								console.log(res)
								that.locationInfo = res
								let parameters = {
									key: that.$config.mapServiceKey,
									locations: that.locationInfo.longitude + ',' + that.locationInfo.latitude,
									coordsys: "gps"
								}
								// https://lbs.amap.com/api/webservice/guide/api/georegeo
								//坐标转换
								uni.request({
									url: "https://restapi.amap.com/v3/assistant/coordinate/convert",
									data: parameters,
									success(res) {
										console.log(res)
										let param = {
											key: that.$config.mapServiceKey,
											location: res.data.locations
										}
										console.log(res)
										uni.request({
											url: 'https://restapi.amap.com/v3/geocode/regeo',
											data: param,
											success: (result) => {
												let data = result.data
												if (data.status == 1) {
													that.locationInfo.address = data.regeocode
														.formatted_address
													that.locationInfo.distance = that
														.getDistance(
															Number(that.sureInfo.latitude),
															Number(that.sureInfo.longitude),
															that.locationInfo.latitude,
															that.locationInfo.longitude);

												} else {
													uni.showModal({
														title: '解析提示',
														content: data.info,
														showCancel: false,
													});
												}
												uni.hideLoading();
											}
										});
									}
								})
							} else {
								uni.hideLoading();
								uni.showModal({
									title: '定位提示',
									content: '获取定位失败',
									showCancel: false,
								});
							}
						},
						fail(err) {
							console.log(err)
							uni.hideLoading();
							uni.showModal({
								title: '定位提示',
								content: '获取定位失败：' + JSON.stringify(err),
								showCancel: false,
							});
						}
					});
				} catch (e) {
					//TODO handle the exception
					console.log('搞什么飞机', e)
				}
			},
			getDistance(lat1, lng1, lat2, lng2) {
				const R = 6371e3; // 地球半径，单位：米
				const radLat1 = lat1 * Math.PI / 180;
				const radLat2 = lat2 * Math.PI / 180;
				const a = radLat1 - radLat2;
				const b = (lng1 * Math.PI / 180) - (lng2 * Math.PI / 180);
				const distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(
					radLat2) * Math.pow(Math.sin(b / 2), 2)));
				return (distance * R).toFixed(2);
			},
			getCurrTimeInterval() {
				setInterval(() => {
					that.getCurrTime()
				}, 1000);
			},
			getCurrTime() {
				const now = new Date();
				that.currTime = now.toLocaleDateString('zh-CN', {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit'
				});
			},
			formatDate(dateString) {
				const date = new Date(dateString);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');

				return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
			},
			loginOut(){
				let that = this;
				uni.$u.http.get('/logout').then(res => {
					if (res.code == 200) {
						uni.removeStorageSync(that.$config.cachePrefix + 'token');
						uni.removeStorageSync(that.$config.cachePrefix + 'user');
						uni.removeStorageSync(that.$config.cachePrefix + 'roles');
						uni.removeStorageSync(that.$config.cachePrefix + 'permissions');
						that.$msg('退出成功', function() {
							uni.$u.route('/pages/login/login');
						});
					}
				});
			},
			// 退出登录
			logout() {
				uni.showModal({
					title: '系统提示',
					content: '您确定要退出系统吗？',
					success: function(res) {
						if (res.confirm) {
							uni.$u.http.get('/logout').then(res => {
								if (res.code == 200) {
									uni.removeStorageSync(that.$config.cachePrefix + 'token');
									uni.removeStorageSync(that.$config.cachePrefix + 'user');
									uni.removeStorageSync(that.$config.cachePrefix + 'roles');
									uni.removeStorageSync(that.$config.cachePrefix + 'permissions');
									that.$msg('退出成功', function() {
										uni.$u.route('/pages/login/login');
									});
								}
							});
						}
					}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.main-container {
		padding: 10px;
		margin: 10px;
		border-radius: 5px;
		background-color: white;

		.title {
			font-size: 18px;
			font-weight: bolder;
		}

		.card-container {
			display: flex;
			justify-content: center;
			margin-top: 20px;
			margin-bottom: 20px;

			.card {
				width: 120px;
				height: 120px;
				line-height: 120px;
				color: white;
				font-size: 18px;
				font-weight: bolder;
				border-radius: 50%;
				background-color: #A52529;
				text-align: center;
			}

			.no-active {
				color: #A52529;
				background-color: #F2F3F5;
			}
		}

		.line {
			margin-top: 10px;
			margin-bottom: 10px;
		}
	}
</style>